package com.bangdao.juc;

/**
 * @author chen
 * @create 2021-01-06
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程，一个线程打印1-52，另一个打印字母A-Z打印顺序为12A34B...5152Z，要求用线程间通信
 * 运行结果12A34B56C78D910E1112F1314G1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z
 */
public class DemoPrintln {
    public static void main(String[] args) {
        ResourceClass resourceClass = new ResourceClass();
        new Thread(() -> {
            resourceClass.println1_52();
        }).start();
        new Thread(() -> {
            resourceClass.printlnA_Z();
        }).start();
    }
}

class ResourceClass {
    //资源起始值
    private static int num = 1;
    //创建可重入所对象
    private ReentrantLock lock = new ReentrantLock();
    private final Condition print1_52Condition = lock.newCondition();
    private final Condition printA_ZCondition = lock.newCondition();

    //打印1-52数字方法
    public void println1_52() {
        //加锁
        lock.lock();
        try {
            for (int i = 1; i < 53; i++) {
                while (num % 3 == 0) {
                    try {
                        //睡 让其他线程先执行
                        print1_52Condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(i);
                num++;
                //唤醒线程
                printA_ZCondition.signalAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    //打印A-Z方法
    public void printlnA_Z() {
        //加锁
        lock.lock();
        try {
            for (char i = 'A'; i <= 'Z'; i++) {
                while (num % 3 != 0) {
                    try {
                        //睡
                        printA_ZCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(i);
                num++;
                //唤醒
                print1_52Condition.signalAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}